package com.evil.file.controller;

import com.evil.common.core.entity.R;
import com.evil.file.service.FileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;

@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping
public class FileController {

    private final FileService fileService;

    /**
     * 下载私密文件
     *
     * @param fileCode  文件code
     * @param timestamp 过期时间
     * @param signature 签名
     * @return R
     */
    @RequestMapping("/download/url")
    public R<?> downloadUrl(@NotBlank(message = "关键参数不能为空") String fileCode,
                            @NotBlank(message = "关键参数不能为空") Long timestamp,
                            @NotBlank(message = "关键参数不能为空") String signature,
                            @NotBlank(message = "关键参数不能为空") String token) {
        return R.success(fileService.getDownloadUrl(fileCode, timestamp, token, signature));
    }

    /**
     * 下载私密文件（重定向）
     * 将会直接暴露OSS访问地址
     *
     * @param fileCode  文件code
     * @param timestamp 过期时间
     * @param signature 签名
     */
    @RequestMapping("/download/redirect")
    public void download(@NotBlank(message = "关键参数不能为空") String fileCode,
                         @NotBlank(message = "关键参数不能为空") Long timestamp,
                         @NotBlank(message = "关键参数不能为空") String signature,
                         @NotBlank(message = "关键参数不能为空") String token,
                         HttpServletResponse response) throws IOException {
        response.sendRedirect(fileService.getDownloadUrl(fileCode, timestamp, token, signature));
    }

    /**
     * 下载私密文件
     * 将会消耗内网带宽
     *
     * @param fileCode  文件code
     * @param timestamp 过期时间
     * @param signature 签名
     */
    @RequestMapping("/download")
    public void downloadFile(@NotBlank(message = "关键参数不能为空") String fileCode,
                             @NotBlank(message = "关键参数不能为空") Long timestamp,
                             @NotBlank(message = "关键参数不能为空") String signature,
                             @NotBlank(message = "关键参数不能为空") String token,
                             HttpServletResponse response) {
        fileService.download(fileCode, timestamp, token, signature, response);
    }
}
